<template>
  <VCard>
    <VToolbar color="primary" dark>
      <VToolbarTitle>咨询安排记录</VToolbarTitle>
    </VToolbar>
    <VCardText>
      <VDataTable :headers="headers" :items="records" :loading="loading">
        <template #item.note="{ item }">
          <VBtn size="small" variant="text" @click="showNote(item.note)">查看</VBtn>
        </template>
        <template #item.scheduled_time="{ item }">
          {{ item.scheduled_time || '-' }}
        </template>
        <template #item.scheduled_place="{ item }">
          {{ item.scheduled_place || '-' }}
        </template>
        <template #item.consultant_name="{ item }">
          {{ item.consultant_name || '未安排' }}
        </template>
        <template #item.risk_level="{ item }">
          <VChip :color="getRiskLevelColor(item.risk_level)" size="small">
            {{ getRiskLevelText(item.risk_level) }}
          </VChip>
        </template>
        <template #item.action="{ item }">
          <VBtn color="primary" size="small" @click="openDialog(item)">安排</VBtn>
        </template>
      </VDataTable>
    </VCardText>
  </VCard>

  <!-- 安排弹窗 -->
  <VDialog v-model="dialog" max-width="600px" @keydown.esc="dialog = false" @click:outside="dialog = false">
    <VCard>
      <VCardTitle>咨询安排</VCardTitle>
      <VCardText>
        <VForm ref="formRef" v-model="formValid">
          <VRow>
            <VCol cols="12">
              <VTextField
                label="预约时间"
                v-model="form.scheduled_time"
                type="datetime-local"
                :rules="[v => !!v || '请选择预约时间']"
                required
              />
            </VCol>
            <VCol cols="12">
              <VSelect
                label="预约地点"
                v-model="form.scheduled_place"
                :items="places"
                :rules="[v => !!v || '请选择预约地点']"
                required
              />
            </VCol>
            <VCol cols="12">
              <VSelect
                label="选择咨询师"
                v-model="form.selected_consultant"
                :items="availableConsultants"
                item-title="display_name"
                item-value="id"
                :rules="[v => !!v || '请选择咨询师']"
                required
                :loading="loadingConsultants"
                :disabled="!form.scheduled_time"
              >
                <template #item="{ props, item }">
                  <VListItem v-bind="props">
                    <template #title>
                      {{ item.raw.consultant_name }}
                    </template>
                    <template #subtitle>
                      {{ formatDutyTime(item.raw.start_time, item.raw.end_time) }} | {{ item.raw.location }}
                    </template>
                  </VListItem>
                </template>
                <template #append>
                  <VBtn
                    icon="mdi-refresh"
                    size="small"
                    variant="text"
                    @click="loadAvailableConsultants(form.scheduled_time)"
                    :disabled="!form.scheduled_time || loadingConsultants"
                    title="刷新咨询师列表"
                  />
                </template>
              </VSelect>
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
      <VCardActions>
        <VSpacer />
        <VBtn color="primary" :disabled="!formValid" @click="handleSubmit">完成</VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 笔记弹窗 -->
  <VDialog v-model="noteDialog" max-width="500px" @keydown.esc="noteDialog = false" @click:outside="noteDialog = false">
    <VCard>
      <VCardTitle>完整笔记</VCardTitle>
      <VCardText>
        <pre style="white-space: pre-wrap;">{{ noteContent }}</pre>
      </VCardText>
      <VCardActions>
        <VSpacer />
        <VBtn color="primary" @click="noteDialog = false">关闭</VBtn>
      </VCardActions>
    </VCard>
  </VDialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getConsultVisitRecords, updateAppointmentArrangement, getAvailableDutySchedules } from '@/api/assistant';
import { useSnackbarStore } from '@/store/snackbarStore';

const snackbarStore = useSnackbarStore();
const loading = ref(false);
const records = ref<any[]>([]);
const dialog = ref(false);
const selected = ref<any>(null);
const form = ref({ 
  scheduled_time: '', 
  scheduled_place: '', 
  selected_consultant: null 
});
const formValid = ref(false);
const formRef = ref();

// 咨询师选择相关
const availableConsultants = ref<any[]>([]);
const loadingConsultants = ref(false);

const noteDialog = ref(false);
const noteContent = ref('');
function showNote(note: string) {
  noteContent.value = note;
  noteDialog.value = true;
}

const headers = [
  { title: '预约ID', key: 'appointment_id' },
  { title: '学号', key: 'student_username' },
  { title: '危机等级', key: 'risk_level' },
  { title: '问题类型', key: 'problem_type' },
  { title: '初访结论', key: 'conclusion' },
  { title: '笔记', key: 'note' },
  { title: '预约时间', key: 'scheduled_time' },
  { title: '预约地点', key: 'scheduled_place' },
  { title: '安排咨询师', key: 'consultant_name' },
  { title: '操作', key: 'action', sortable: false }
];

const places = [
  '心理咨询中心101室',
  '心理咨询中心102室',
  '心理咨询中心201室',
  '心理咨询中心202室'
];

const getRiskLevelText = (riskLevel: string) => {
  const riskMap: Record<string, string> = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高',
    'CRITICAL': '严重'
  };
  return riskMap[riskLevel] || riskLevel;
};

const getRiskLevelColor = (riskLevel: string) => {
  const colorMap: Record<string, string> = {
    'LOW': 'success',
    'MEDIUM': 'warning',
    'HIGH': 'error',
    'CRITICAL': 'error'
  };
  return colorMap[riskLevel] || 'default';
};

// 格式化值班时间
function formatDutyTime(startTime: string, endTime: string) {
  if (!startTime || !endTime) return '';
  const start = new Date(startTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  const end = new Date(endTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  return `${start}-${end}`;
}

// 根据预约时间查询可用的咨询师
async function loadAvailableConsultants(appointmentTime: string) {
  if (!appointmentTime) {
    availableConsultants.value = [];
    return;
  }
  
  loadingConsultants.value = true;
  try {
    // 将datetime-local格式转换为数据库格式
    const formattedTime = appointmentTime.replace('T', ' ');
    
    console.log('查询咨询师时间:', formattedTime);
    
    const response = await getAvailableDutySchedules(formattedTime);
    console.log('咨询师查询响应:', response);
    
    if (response.data && response.data.code === 200) {
      availableConsultants.value = response.data.data.map((item: any) => ({
        ...item,
        display_name: `${item.consultant_name} (${formatDutyTime(item.start_time, item.end_time)})`
      }));
      console.log('可用咨询师:', availableConsultants.value);
    } else {
      availableConsultants.value = [];
      console.log('未找到可用咨询师');
    }
  } catch (error) {
    console.error('获取可用咨询师失败:', error);
    availableConsultants.value = [];
    snackbarStore.showMessage('获取可用咨询师失败');
  } finally {
    loadingConsultants.value = false;
  }
}

async function openDialog(item: any) {
  selected.value = item;
  form.value.scheduled_time = item.scheduled_time || '';
  form.value.scheduled_place = item.scheduled_place || '';
  form.value.selected_consultant = null;
  availableConsultants.value = [];
  dialog.value = true;
  
  // 如果有预约时间，立即查询可用的咨询师
  if (form.value.scheduled_time) {
    await loadAvailableConsultants(form.value.scheduled_time);
  }
}

async function loadData() {
  loading.value = true;
  try {
    const res = await getConsultVisitRecords();
    if (res.data && res.data.code === 200) {
      // 需要补充scheduled_time和scheduled_place
      records.value = res.data.data.map((rec: any) => ({
        ...rec,
        scheduled_time: rec.scheduled_time,
        scheduled_place: rec.scheduled_place
      }));
    }
  } finally {
    loading.value = false;
  }
}

async function handleSubmit() {
  if (!formValid.value || !selected.value) return;
  
  try {
    // 获取选中的咨询师信息
    const selectedConsultant = availableConsultants.value.find(c => c.id === form.value.selected_consultant);
    
    await updateAppointmentArrangement(
      selected.value.appointment_id,
      form.value.scheduled_time,
      form.value.scheduled_place,
      selectedConsultant ? selectedConsultant.user_id : undefined
    );
    
    // 如果有选择咨询师，记录日志
    if (selectedConsultant) {
      console.log('选择的咨询师:', selectedConsultant.consultant_name);
    }
    
    snackbarStore.showMessage('安排更新成功');
    dialog.value = false;
    loadData();
  } catch (error) {
    snackbarStore.showMessage('安排更新失败');
  }
}

onMounted(loadData);
</script> 